<template>
  <div class="container">
    <a-card class="custom-card" title="">
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="query"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
            label-align="left"
          >
            <a-row :gutter="16">
              <a-col flex="220px">
                <a-input v-model="query.ip" placeholder="请输入IP" allow-clear>
                  <template #prepend>IP</template>
                </a-input>
              </a-col>
              <a-col flex="360px">
                <a-input-group>
                  <a-select v-model="query.time_type" placeholder="时间类型" :style="{width:'120px'}">
                    <a-option value="created_at" label="添加时间" />
                  </a-select>
                  <a-range-picker v-model="query.range_date" allow-clear/>
                </a-input-group>
              </a-col>
              <a-col :span="4">
                <a-space :size="5">
                  <a-button type="primary" @click="search"><template #icon><icon-search /></template>搜索</a-button>
                  <a-button status="success" @click="refresh()"><template #icon><icon-refresh /></template>重置</a-button>
                  <a-dropdown>
                    <a-button>批量操作 <icon-down/></a-button>
                    <template #content>
                      <a-doption @click="batchDel()"><template #icon><icon-delete /></template>批量删除</a-doption>
                    </template>
                  </a-dropdown>
                </a-space>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
      </a-row>
      <a-divider style="margin-top: 10px" />
      <a-table
        row-key="id"
        :loading="loading"
        :pagination="pagination"
        :data="renderData"
        :columns="columns"
        :bordered="{ wrapper: true, cell: true }"
        :row-selection="rowSelection"
        :scroll="tableScroll"
        column-resizable
        @selection-change="selectionChange"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <template #operations="{ record }">
          <a-space>
            <a-button type="primary" status="danger" size="small" @click="del([record])"><template #icon><icon-delete /></template>删除</a-button>
          </a-space>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, h, compile } from 'vue';
  import { useI18n } from 'vue-i18n';
  import { Message, Modal } from '@arco-design/web-vue';

  import useLoading from '@/hooks/loading';
  import screenHeight from '@/utils/screen-height';
  import { Pagination } from '@/types/global';
  import { DataState, QueryParams, apiList, apiDel } from '@/api/log';

  const { loading, setLoading } = useLoading(true);
  const { t } = useI18n();
  const height = screenHeight(235);
  const basePagination: Pagination = {
    current: 1,
    pageSize: 20,
    showTotal: true,
    showJumper: true,
    showPageSize: true,
    pageSizeOptions: [10, 20, 30, 50, 100, 150, 200, 300, 500],
  };
  const baseQuery = () => {
    return {
      page: 1,
      limit: 20,
      ip: '',
      time_type: 'created_at',
      range_date: [],
    };
  };

  const columns = reactive([
    {
      title: 'ID', dataIndex: 'id', width: 80,
      align: 'center' as 'left' | 'right' | 'center',
      fixed: 'left' as 'left' | 'right',
      sortable: {sortDirections: ['ascend', 'descend'] as ('ascend' | 'descend')[]},
    },
    {
      title: '操作IP', dataIndex: 'ip', width: 120,
      align: 'center' as 'left' | 'right' | 'center',
    },
    {
      title: '操作详细', dataIndex: 'info', width: 300,
      align: 'center' as 'left' | 'right' | 'center',
    },
    {
      title: '创建时间', dataIndex: 'created_at', width: 180,
      align: 'center' as 'left' | 'right' | 'center',
      sortable: {sortDirections: ['ascend', 'descend'] as ('ascend' | 'descend')[]},
    },
    {
      title: '操作', dataIndex: 'operations', width: 80,
      align: 'center' as 'left' | 'right' | 'center',
      fixed: 'right' as 'left' | 'right',
      slotName: 'operations',
    },
  ]);
  const renderData = ref<DataState[]>([]);
  const query = ref(baseQuery());
  const pagination = reactive({
    ...basePagination,
  });
  const rowSelection = reactive({
    type: 'checkbox' as const,
    selectedRowKeys: [] as any,
    showCheckedAll: true,
  });
  const tableScroll = ref({
    x: '100%',
    y: `${height}px`,
  });

  const isReset = ref(true); // 是否重置
  let selectionKeys: string[] = []; // 选中项ID

  // 分页
  const onPageChange = (page: number) => {
    isReset.value = false;
    fetchData({ ...query.value, page });
  };
  const onPageSizeChange = (limit: number) => {
    isReset.value = false;
    fetchData({ ...query.value, limit });
  };
  // 列表
  const fetchData = async (
    params: QueryParams = { ...query.value }
  ) => {
    setLoading(true);
    reset();
    try {
      const { data } = await apiList(params);
      renderData.value = data.data;
      query.value.page = params.page;
      query.value.limit = params.limit;
      pagination.current = params.page;
      pagination.pageSize = params.limit;
      pagination.total = data.total;
    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };
  // 删除
  const del = (row: any[]) => {
    if (!row.length) {
      selectMsg();
    } else {
      let title = '删除';
      let message = `确定要删除选中的 <span style="color:red">${row.length} </span> 条数据吗？`;
      let ids = row;
      if (row.length === 1 && row[0].id) {
        title = `${title}ID：${row[0].id}`;
        message = `确定要删除 <span style="color:red">${row[0].id} </span> 这条数据吗？`;
        ids = [row[0].id];
      }
      Modal.warning({
        title,
        content: () => h(compile(message)),
        closable: true,
        hideCancel: false,
        onOk: (async () => {
          setLoading(true);
          try {
            await apiDel({ids});
          } catch (err) {
            setLoading(false);
          } finally {
            fetchData({...query.value});
            setLoading(false);
          }
        }),
      });
    }
  };
  // 重置
  const reset = async () => {
    if (isReset.value) {
      rowSelection.selectedRowKeys = [];
      selectionKeys = [];
    } else {
      isReset.value = true;
    }
  };
  // 搜索
  const search = () => {
    query.value.page = 1;
    fetchData({...query.value} as unknown as QueryParams);
  };
  // 刷新
  const refresh = () => {
    query.value = baseQuery();
    fetchData({...query.value});
  };

  // 已选择的数据行发生改变时触发 -- table 表头
  const selectionChange = (rowKeys: any[]) => {
    rowSelection.selectedRowKeys = rowKeys;
    selectionKeys = rowKeys;
  };
  const selectMsg = (message?: string) => {
    Message.info(message || '请选择需要操作的数据');
  };
  // 批量删除
  const batchDel = () => {
    del(selectionKeys);
  };

  fetchData();
</script>

<script lang="ts">
  export default {
    name: 'Log',
  };
</script>

<style scoped lang="less">
  :deep(.arco-table-th) {
    &:last-child {
      .arco-table-th-item-title {
        margin-left: 16px;
      }
    }
  }
</style>
